﻿using Caliburn.Micro;
using MCPlatform.Builder.WorkStation.StationEvents;
using MCPlatform.Builder.WorkStation.StationEvents.Home;
using MCPlatform.Builder.WorkStation.StationEvents.MainControl;
using MCPlatform.Components.Utilities;
using MCPlatform.MotionLib.Base;
using MCPlatform.ViewModels.Shell;
using Panuon.WPF.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls.Primitives;

namespace MCPlatform.Builder.WorkStation
{
    public class MainControlStation : WorkStationBase,IHandle<HomeToMainControlEvent>
    {
        #region Properties

        public IIO StartButton { get; set; }

        public IIO StopButton { get; set; }

        public IIO ResetButton { get; set; }

        public IIO ManualSwitch { get; set; }
        public IIO Estop { get; set; }

        public IIO StartLed { get; set; }

        public IIO StopLed { get; set; }

        public IIO ResetLed { get; set; }

        public IIO RedLed { get; set; }

        public IIO YellowLed { get; set; }

        public IIO GreenLed { get; set; }

        public IIO Buzzer { get; set; }


        public IIO FrontSafetyGrating { get; set; }

        public IIO RearSafetyGrating { get; set; }

        public IIO SafetyOpto { get; set; }


        #endregion


        #region Event

       // public event System.Action? StartEvent;

       // public event Action? StopEvent;

       // public event System.Action? ResetEvent;


        // public event Action? PauseEvent;


        #endregion


        #region Fields

        private Timer timer = new Timer() { Enabled=true,Interval=10};

        private bool eStop = false;
        private bool isEStop = false;

        private bool safetyOpto = false;
        private bool issafetyOpto = false;
        #endregion


        #region CTOR
        private static MainControlStation? instance;

        private static readonly object lockObject = new object();

        private MainControlStation()
        {
            //1.映射基本信息
            WorkStationModel = WorkStation.Instance.WorkStationDic[0];
          

            StartButton = IOModels[0].IOEntity!;
            StopButton = IOModels[1].IOEntity !;
            ResetButton = IOModels[2].IOEntity!;
            ManualSwitch = IOModels[3].IOEntity !;

            Estop = IOModels[4].IOEntity!;

            FrontSafetyGrating = IOModels[5].IOEntity!;
            RearSafetyGrating = IOModels[6].IOEntity!;

            StartLed = IOModels[7].IOEntity!;
            StopLed = IOModels[8].IOEntity!;
            ResetLed = IOModels[9].IOEntity!;

            


            RedLed = IOModels[11].IOEntity!;
            YellowLed = IOModels[13].IOEntity!;
            GreenLed = IOModels[12].IOEntity!;
            Buzzer = IOModels[14].IOEntity!;

            SafetyOpto = IOModels[15].IOEntity!;



            timer.Start();
            //timer.Elapsed += Timer_Elapsed;

            //HomeViewModel.ResetEvent += HomeViewModel_ResetEvent;
            //HomeViewModel.SafetyOptpEvent += HomeViewModel_SafetyOptpEvent;


        }

        private bool HomeViewModel_SafetyOptpEvent()
        {
            return !SafetyOpto.Value;
        }

        private bool HomeViewModel_ResetEvent()
        {
            return !Estop.Value;
        }

        private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            E_stopScan();
            ButtonScan();
            SafetyOptoScan();

        }

        public static MainControlStation Instance
        {
            get
            {
                lock (lockObject)
                {
                    if (instance == null)
                    {
                        instance = new MainControlStation();
                    }
                    return instance;
                }
            }
        }

        public override void RegisterEvent()
        {
            StartButton.RisingEvent += StartButton_RisingEvent;
            StopButton.RisingEvent += StopButton_RisingEvent;
            ResetButton.RisingEvent += ResetButton_RisingEvent;
            ManualSwitch.RisingEvent += ManualSwitch_RisingEvent;

            FrontSafetyGrating.FallingEvent += SafetyGrating_FallingEvent;
            RearSafetyGrating.FallingEvent += SafetyGrating_FallingEvent;

           
        }

      
        private async void SafetyGrating_FallingEvent(object obj)
        {

            LogModel.LogInfo = "安全光栅触发！";
            await Send(new MainControlToHomeEvent() { MessageType = StationEvents.MessageType.Unsafty });
        }

        private async void ManualSwitch_RisingEvent(object obj)
        {
            LogModel.LogInfo = "手动模式触发！";
            await Send(new MainControlToHomeEvent() { MessageType = StationEvents.MessageType.Manual });
            //StopLed.Value = false;
            //StartLed.Value = true;
            ManualStatus();

        }

        private async void StartButton_RisingEvent(object obj)
        {
            if (ManualSwitch.Value)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    MessageBoxX.Show("请先把旋钮开关旋至自动！");
                });
               
                return;
            }

            var res =  await Send(new MainControlToHomeEvent() { MessageType=StationEvents.MessageType.NotifyStart});
            if (res)
            {
                StartLed.Value = false;
                StopLed.Value = true;
            }
        }

        private async void StopButton_RisingEvent(object obj)
        {
            if (ManualSwitch.Value)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    MessageBoxX.Show("请先把旋钮开关旋至自动！");
                });

                return;
            }
            var res =  await Send(new MainControlToHomeEvent() { MessageType = StationEvents.MessageType.NotifyStop });
            if (res)
            {
                StopLed.Value = false;
                StartLed.Value = true;
            }
        }
        private async void ResetButton_RisingEvent(object obj)
        {
           var res =  await Send(new MainControlToHomeEvent() { MessageType = StationEvents.MessageType.NotifyReset });
            if (res)
            {
                ResetLed.Value = false;
                InitialStatus();
            }
        }





        #endregion CTOR



        #region Override Methods

        public override Task DryRun()
        {
            return Task.CompletedTask;
        }

        public override Task Execute()
        {
            return Task.CompletedTask;
        }

        public override Task Initial()
        {
            LogModel.LogInfo = "初始化完成！";
            LogModel.Status = Shared.Enums.WorkStationStatus.Idle;
            return Task.CompletedTask;
        }

        public override Task<bool> IsSaftyToMove()
        {

            return Task.FromResult(true);
        }      

        public override Task Test()
        {
            return Task.CompletedTask;
        }

        public override Task Clear(bool isClear)
        {
            return Task.CompletedTask;
        }

        public override Task ResetSignal()
        {
            return Task.CompletedTask;
        }

        public override void StationStop()
        {
            ;
        }


        public new  async Task<bool> Send(EventBase? request)
        {
            
            if (request is null)
            {
                return false;
            }
            await EventAggregator.PublishOnUIThreadAsync(request);
            return await request.TaskCompletionSource.Task;
        }

        #endregion



        #region 主控方法

        private void E_stopScan()
        {
            eStop = Estop.Value;
            if (!eStop)
            {
                if (!isEStop)
                {
                    isEStop = true;
                    StopTrigger("急停触发！");
                }

            }
            else
            {
                isEStop = false;
            }
        }

        private void SafetyOptoScan()
        {
            safetyOpto = SafetyOpto.Value;
            if (!safetyOpto)
            {
                if (!issafetyOpto)
                {
                    issafetyOpto = true;
                    StopTrigger("龙门防撞光电触发！");
                }

            }
            else
            {
                issafetyOpto = false;
            }
        }

        private void ButtonScan()
        {
            _ = StartButton.Value;
            _ = StopButton.Value;
            _ = ResetButton.Value;
            _ = ManualSwitch.Value;
            _ = RearSafetyGrating.Value;
            _ = FrontSafetyGrating.Value;
            

        }

        public void RunningStatus()
        {
            LogModel.LogInfo = "运行中！";
            GreenLed.Value = true;
            YellowLed.Value = false;
            RedLed.Value = false;
            Buzzer.Value = false;
            StopLed.Value = true;
            StartLed.Value = false;
            
        }


        public void IdleStatus()
        {
            LogModel.LogInfo = "初始化完成！";
            GreenLed.Value = false;
            YellowLed.Value = true;
            RedLed.Value = false;
            Buzzer.Value = false;
            StopLed.Value = false;
            StartLed.Flipper = true;

        }

        public void ErrorStatus()
        {
           
            GreenLed.Value = false;
            YellowLed.Value = false;
            RedLed.Value = true;        
            Buzzer.Flipper = true;          
            ResetLed.Flipper = true;
        }

        public void PauseStatus()
        {
           // LogModel.LogInfo = "暂停中！";
            GreenLed.Value = false;
            YellowLed.Value = true;
            RedLed.Value = false;
            Buzzer.Value = false;
            StopLed.Value = false;
            StartLed.Value = true;
        }


        public void ShortageStatus()
        {
            LogModel.LogInfo = "缺料！";
            GreenLed.Value = false;
            YellowLed.Flipper = true;
            RedLed.Value = false;
            Buzzer.Flipper = true;
            
        }


        public void FullStatus()
        {
            LogModel.LogInfo = "下料码垛满料！";
            GreenLed.Value = false;
            YellowLed.Flipper = true;
            RedLed.Value = false;
            Buzzer.Flipper = true;

        }


        public void RetryStatus()
        {
            LogModel.LogInfo = "重试提示！";
            GreenLed.Value = false;
            YellowLed.Flipper = true;
            RedLed.Value = false;
            Buzzer.Flipper = true;

        }


        public void InitialStatus()
        {
            GreenLed.Value = false;
            YellowLed.Flipper = true;
            RedLed.Value = false;
            Buzzer.Flipper = false;
            StopLed.Value = true;
            StartLed.Value = false;
        }


        public void ManualStatus()
        {
            LogModel.LogInfo = "手动模式触发！";
            GreenLed.Value = false;
            YellowLed.Value = true;
            RedLed.Value = false;
            Buzzer.Value = false;
            StopLed.Value = false;
            StartLed.Value = true;
        }


        #endregion


        #region Event Handler

        public Task HandleAsync(HomeToMainControlEvent message, System.Threading.CancellationToken cancellationToken)
        {
            if (message.MessageType == MessageType.NotifyStart)
            {
                Logger.Debug("NotifyStart");
                RunningStatus();
            }
            else if (message.MessageType == MessageType.NotifyStop)
            {
                Logger.Debug("NotifyStop");
                ErrorStatus();
            }
            else if (message.MessageType == MessageType.NotifyResume)
            {
                Logger.Debug("NotifyResume");
                RunningStatus();
            }
            else if (message.MessageType == MessageType.NotifyInitialResume)
            {
                Logger.Debug("NotifyInitialResume");
                InitialStatus();
            }
            else if (message.MessageType == MessageType.NotifyPause)
            {
                Logger.Debug("NotifyPause");
                PauseStatus();
            }
            else if (message.MessageType == MessageType.Initial)
            {
                Logger.Debug("Initial");
                InitialStatus();
                
            }
            else if (message.MessageType == MessageType.NotifyShortage)
            {
                Logger.Debug("NotifyShortage");
                ShortageStatus();
            }
            else if (message.MessageType == MessageType.NotifyTrayEmpty)
            {
                Logger.Debug("NotifyTrayEmpty");
                RunningStatus();
            }
            else if (message.MessageType == MessageType.NotifyTrayFull)
            {
                Logger.Debug("NotifyTrayFull");
                FullStatus();
            }

            else if (message.MessageType == MessageType.Manual)
            {
                Logger.Debug("Manual");
                ManualStatus();
            }
            else if (message.MessageType == MessageType.NotifyRetry)
            {
                Logger.Debug("NotifyRetry");
                RetryStatus();
            }
            else if (message.MessageType == MessageType.NotifyIdle)
            {
                Logger.Debug("NotifyIdle");
                IdleStatus();

            }
            else if (message.MessageType == MessageType.RequestAuto)
            {
                Logger.Debug("RequestAuto");
                message.TaskCompletionSource?.SetResult(!ManualSwitch.Value);
                return Task.CompletedTask;

            }
            else if (message.MessageType == MessageType.NotifyReset)
            {
                Logger.Debug("Reset");
                ResetLed.Value = false;
                InitialStatus();
            }

            message.TaskCompletionSource?.SetResult(true);

            return Task.CompletedTask;
        }

        #endregion



    }
}
